package com.xzy.controller;

import com.xzy.config.Audience;
import com.xzy.entity.User;
import com.xzy.service.UserService;
import com.xzy.utils.JSONResult;
import com.xzy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Audience audience;

    @PostMapping("/question/user/login")
    public JSONResult login(@RequestParam("userName") String userName, @RequestParam("password") String password, HttpServletResponse response)
    {
          int pass=Integer.parseInt(password);
          if(pass!=113798)
          {
             return JSONResult.ERROR("登录密码错误！");
          }
          else
          {
              User user=userService.login(userName);
              if(user==null)
              {
                  return JSONResult.ERROR("没有此用户！");
              }
              else
              {
                  String tUserId=Integer.toString(user.getUserId());
                  String token= JWTUtils.createJWT(tUserId,userName,audience);
                  response.setHeader(JWTUtils.AUTH_HEADER_KEY,JWTUtils.TOKEN_PREFIX+token);
                  Map<String,String> map=new HashMap<String,String>();
                  map.put("token",token);
                  return JSONResult.SUCCESS(map);
              }
          }
    }

    @GetMapping("/question/user/getUser")
    public JSONResult getUser(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        String _userId = JWTUtils.getUserId(token, audience.getBase64Secret());
        int userId = Integer.parseInt(_userId);
        User user=userService.getUser(userId);
        return JSONResult.SUCCESS(user);
    }



}
